//
//  LocationModel.m
//  huashiedu
//
//  Created by oceans on 2018/8/27.
//  Copyright © 2018年 hema. All rights reserved.
//

#import "LocationModel.h"
#import <UIKit/UIKit.h>
#import "AppDelegate.h"

static LocationModel *shared;

@interface LocationModel () <TencentLBSLocationManagerDelegate>

@property (strong, nonatomic) TencentLBSLocationManager *locationManager;
@property (strong, nonatomic) CLLocationManager *clManager;
@end

@implementation LocationModel

+ (instancetype)shared {
    
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        shared = [[LocationModel alloc] init];
    });
    return shared;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        shared = [super allocWithZone:zone];
    });
    return shared;
}

- (id)copyWithZone:(NSZone *)zone {
    return shared;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup {
    
    self.locationManager = [[TencentLBSLocationManager alloc] init];
    
    [self.locationManager setDelegate:self];
    
    [self.locationManager setApiKey:@"OAZBZ-7HX35-FMGID-Q6CPW-I3Q5Q-TZB7B"];
    
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    
    // 需要后台定位的话，可以设置此属性为YES。
    [self.locationManager setAllowsBackgroundLocationUpdates:NO];
    
    // 如果需要POI信息的话，根据所需要的级别来设定，定位结果将会根据设定的POI级别来返回，如：
    [self.locationManager setRequestLevel:TencentLBSRequestLevelName];
    
    // 申请的定位权限，得和在info.list申请的权限对应才有效
    CLAuthorizationStatus authorizationStatus = [CLLocationManager authorizationStatus];
    if (authorizationStatus == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestWhenInUseAuthorization];
    }
    
    self.cityName = @"";
    self.cityNumber = @"";
    self.areaName = @"定位中...";
    self.areaNumber = @"";
    [self getSave];
    [self startSingleLocation];
}

- (void)getSave {
    NSUserDefaults *stand = [NSUserDefaults standardUserDefaults];
    NSString *cityName = [stand objectForKey:@"city_name"];
    NSString *cityNumber = [stand objectForKey:@"city_number"];
    NSString *areaName = [stand objectForKey:@"area_name"];
    NSString *areaNumber = [stand objectForKey:@"area_number"];
    if (cityName) {
        self.cityName = cityName;
    }
    if (cityNumber) {
        self.cityNumber = cityNumber;
    }
    if (areaName) {
        self.areaName = areaName;
    }
    if (areaNumber) {
        self.areaNumber = areaNumber;
    }
}

- (CLAuthorizationStatus)status {
    return [CLLocationManager authorizationStatus];
}

// 单次定位
- (void)startSingleLocation {
    
    __weak typeof(self) weakself = self;
    [self.locationManager requestLocationWithCompletionBlock:
     ^(TencentLBSLocation *location, NSError *error) {
         
         if (location != nil && (weakself.areaNumber == nil || weakself.areaNumber.length == 0)) {
             weakself.cityName = location.city;
             weakself.areaName = location.district;
             weakself.areaNumber = location.code;
             [weakself save];
             [[NSNotificationCenter defaultCenter] postNotificationName:locationModelChangedNotification object:nil];
         }
     }];
}

// 连续定位
- (void)startSerialLocation {
    //开始定位
    [self.locationManager startUpdatingLocation];
}

- (void)stopSerialLocation {
    //停止定位
    [self.locationManager stopUpdatingLocation];
}

- (void)tencentLBSLocationManager:(TencentLBSLocationManager *)manager
                 didFailWithError:(NSError *)error {
    CLAuthorizationStatus authorizationStatus = [CLLocationManager authorizationStatus];
    if (authorizationStatus == kCLAuthorizationStatusDenied ||
        authorizationStatus == kCLAuthorizationStatusRestricted) {
        
        self.cityName = @"";
        self.cityNumber = @"";
        self.areaName = @"无法定位";
        self.areaNumber = @"";
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"定位权限未开启，是否开启？" preferredStyle:UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:nil]];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @YES} completionHandler:nil];
            }
        }]];
        
        [[(AppDelegate *)[[UIApplication sharedApplication] delegate] root] presentViewController:alert animated:YES completion:nil];
        
    } else {
        
        self.cityName = @"";
        self.cityNumber = @"";
        self.areaName = @"未知";//[error localizedDescription];
        self.areaNumber = @"";
    }
}

- (void)tencentLBSLocationManager:(TencentLBSLocationManager *)manager
                didUpdateLocation:(TencentLBSLocation *)location {
    //定位结果
    NSLog(@"location:%@", location.location);
}

- (void)save {
    NSUserDefaults *stand = [NSUserDefaults standardUserDefaults];
    [stand setObject:self.cityNumber forKey:@"city_number"];
    [stand setObject:self.cityName forKey:@"city_name"];
    [stand setObject:self.areaNumber forKey:@"area_number"];
    [stand setObject:self.areaName forKey:@"area_name"];
}

- (void)fresh {
    [self save];
    [[NSNotificationCenter defaultCenter] postNotificationName:locationModelChangedNotification object:nil];
}

@end
